/**
 * 文件上传工具类
 * 解析文件的值为Json对象
 * 作者:郭海涛
 * 用法:
 * import {UploadUtil} from "@/utils/uploadUtil"
 * console.log(UploadUtil.decodeFileItem1(encodedFileItem))
 */
import { Base64 } from 'js-base64';
export const apiUrl = process.env.BASE_API;

const downloadUrl = apiUrl + '/download';
export const uploadUrl = apiUrl + '/upload';
export class UploadUtil {
  //解码文件上传的值 返回数组
  static decodeFileItem(encodedFileItem) {
    let fileList = [];
    if (encodedFileItem) {
      let items = (encodedFileItem + '').split('|');
      items.forEach(item => {
        try {
          let fileItem = JSON.parse(Base64.decode(item));
          fileList.push({
            id: fileItem.id,
            encodedItem: item,
            fileName: fileItem.fileName,
            userName: fileItem.userName,
            time: fileItem.time,
            fileSize: fileItem.fileSize,
            name: fileItem.fileName + '(' + fileItem.fileSize + ')',
            url: downloadUrl + '/' + item,
          });
        } catch (e) {
          console.error('解析文件上传参数错误.', item);
        }
      });
    }
    return fileList;
  }

  //解析单个文件 返回JSON对象
  static decodeFileItem1(encodedFileItem) {
    let fileList = UploadUtil.decodeFileItem(encodedFileItem);
    if (fileList.length > 0) {
      return fileList[0];
    }
    return null;
  }

  //编码文件上传对象
  static encodeFileItem(fileItem) {
    return Base64.encodeURI(JSON.stringify(fileItem));
  }

  static imageUrl(imagePath) {
    if (!imagePath) return '';
    return apiUrl + '/image' + imagePath.split('|')[0];
  }
}
